import fs from 'fs'
import matter from 'gray-matter'
import highLightJs from 'highlight.js'
import marked from 'marked'
import { join } from 'path'
import PostType from '@/types/post'

marked.setOptions({
  highlight: function (code, lang) {
    const language = highLightJs.getLanguage(lang) ? lang : 'plaintext'
    return highLightJs.highlight(code, { language }).value
  },
  langPrefix: 'hljs language-',
})

const postsDirectory = join(process.cwd(), '_posts')

export const getAllSlugs: () => string[] = () => {
  return fs
    .readdirSync(postsDirectory)
    .map((slug) => slug.replace(/\.md$/, ''))
    .filter((slug) => !['about', 'template'].includes(slug))
}

export const getPostBySlug: (slug: string) => PostType = (slug) => {
  const fullPath = join(postsDirectory, `${slug}/index.md`)
  const fileContents = fs.readFileSync(fullPath, 'utf8')
  const { data, content } = matter(fileContents)
  const { titleImage, excerpt, ...props } = data

  const htmlContent = marked(content, {
    baseUrl: `/md-images/${slug}/`,
    breaks: true,
  })

  let absoluteTitleImage = ''

  if (titleImage) {
    absoluteTitleImage = titleImage.includes('http')
      ? titleImage
      : `/md-images/${slug}/${titleImage}`
  }

  const post = {
    slug,
    titleImage: absoluteTitleImage,
    excerpt: excerpt || htmlContent.replace(/<[^>]*>/g, '').slice(0, 150),
    content: htmlContent,
    ...props,
  } as PostType

  return post
}

export const getAllPosts: (sort?: 'asc' | 'desc') => PostType[] = (
  sort = 'desc'
) => {
  const slugs = getAllSlugs()

  let allPosts = slugs.map((slug) => getPostBySlug(slug))

  if (sort) {
    allPosts = allPosts.sort((postA, postB) => {
      const dateA = new Date(postA.date)
      const dateB = new Date(postB.date)
      return sort === 'desc'
        ? dateB.getTime() - dateA.getTime()
        : dateA.getTime() - dateB.getTime()
    })
  }

  return allPosts
}

export const getLatestPosts: (length?: number) => PostType[] = (length = 6) => {
  return getAllPosts().slice(0, length)
}
